package log

import (
	"fmt"
	"io"
	"strings"

	"gitee.com/yrwy/go-log"
)

type Writer log.Logger

type defaultWriter struct {
}

func attachLn(s string) string {
	if strings.HasSuffix(s, "\n") {
		return s
	}
	return s + "\n"
}

func (defaultWriter) Close() error {
	return nil
}

func (x defaultWriter) Log(lv log.Level, args ...any) error {
	_, err := fmt.Println(args...)
	return err
}
func (x defaultWriter) Logf(lv log.Level, format string, args ...any) error {
	_, err := fmt.Print(attachLn(fmt.Sprintf(format, args...)))
	return err
}

func (x defaultWriter) Logr(lv log.Level, r io.Reader) error {
	return x.LogDepthr(2, lv, r)
}

// 自定义calldepth，顶层从0开始计算
func (x defaultWriter) LogDepth(calldepth int, lv log.Level, args ...any) error {
	_, err := fmt.Println(args...)
	return err
}

func (x defaultWriter) LogDepthf(calldepth int, lv log.Level, format string, args ...any) error {
	_, err := fmt.Print(attachLn(fmt.Sprintf(format, args...)))
	return err
}

func (x defaultWriter) LogDepthr(calldepth int, lv log.Level, r io.Reader) error {
	buf, err := io.ReadAll(r)
	if err != nil {
		return err
	}
	_, err = fmt.Print(attachLn(string(buf)))
	return err
}
